package tr.edu.yildiz.ce.app_manager.ui.components.form;

import tr.edu.yildiz.ce.app_manager.service.BasicService;
import tr.edu.yildiz.ce.app_manager.ui.AppManagerApplication;
import tr.edu.yildiz.ce.app_manager.ui.action.menu.MenuAction;
import tr.edu.yildiz.ce.app_manager.ui.action.menu.MenuActionFactory;

import com.vaadin.ui.Button;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Button.ClickEvent;

public class BasicForm<M> extends Form {

	private Button save = new Button("Save");
    private Button cancel = new Button("Cancel");
    
    M model;
    AppManagerApplication app;
    MenuActionFactory menuActionFactory = new MenuActionFactory();
    
    public BasicForm(AppManagerApplication app) {
		this.app = app;
	}
    
    protected void preSave(){
    	
    }
	
    protected void preCancel(){
    	
    }
    
	protected void initButtons() {
		save.addListener(new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				BasicService service = app.getServiceProvider().getService(
						model.getClass());
				preSave();
				service.persist(model);
			}
		});

		cancel.addListener(new Button.ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				MenuAction menuAction = menuActionFactory.getTableAction(model.getClass(), app);
				preCancel();
				menuAction.doAction();
			}
		});

		HorizontalLayout footer = new HorizontalLayout();
		footer.setSpacing(true);
		footer.addComponent(save);
		footer.addComponent(cancel);
		setFooter(footer);

	}
    
    
}
